package com.aboverock.core.spring.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.aboverock.common.constant.KbsmartConstant;
import com.aboverock.common.domain.Result;
import com.aboverock.common.helper.PageHelper;
import com.aboverock.common.utils.ReflectionUtils;
import com.aboverock.core.orm.domain.BaseEntity;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

public abstract class BaseController<T extends BaseEntity<?>, S extends IService<T>> {
    
    protected static final String CURRENT_PAGE_DEFAULT = KbsmartConstant.Pagination.CURRENT_PAGE_DEFAULT + "";
    protected static final String PAGE_SIZE_DEFAULT = KbsmartConstant.Pagination.PAGE_SIZE_DEFAULT + "";

    @Autowired
    protected S baseService;

    /**
     * 分页查询.
     *
     * @param request the request
     * @return 分页查询结果
     */
    @ApiOperation(value = "分页获取数据信息")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "current", value = "当前页码", defaultValue = CURRENT_PAGE_DEFAULT, required = false, dataType = "long"),
        @ApiImplicitParam(name = "pageSize", value = "每页数量", defaultValue = PAGE_SIZE_DEFAULT, required = false, dataType = "long"),
        @ApiImplicitParam(name = "sort", value = "字段排序：column1,column3,order1;column2,order2", required = false, paramType = "query") })
    @GetMapping
    public Result page(HttpServletRequest request) {
        Page<T> page = PageHelper.page(ReflectionUtils.getClassGenricType(getClass()));
        baseService.page(page, null);
        return Result.success(page);
    }

    /**
     * 查询所有数据.
     *
     * @param request the request
     * @return 查询数据的结果列表
     */
    @ApiOperation(value = "获取所有数据信息")
    @GetMapping("all")
    public Result all(HttpServletRequest request) {
        List<T> list = baseService.list(null);
        return Result.success(list);
    }

    /**
     * 插入新数据.
     *
     * @param entity the entity
     * @return the result
     */
    @ApiOperation(value = "新增数据")
    @PostMapping
    public Result save(@Valid @RequestBody T entity) {
        if (baseService.save(entity)) {
            return Result.success(entity);
        }
        return Result.fail();
    }

}
